package com.example.leetdemo.graph.done;

public class Solution733 {

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int color = image[sr][sc];
        int[][] move = new int[image.length][image[0].length];
        scrawl(image, sr, sc, newColor, color, move);
        return image;
    }

    private void scrawl(int[][] image, int x, int y, int target, int source, int[][] move) {
        if (x < 0 || y < 0 || x == image.length || y == image[0].length) {
            return;
        }
        if (image[x][y] != source || move[x][y] == 1) {
            return;
        }
        image[x][y] = target;
        move[x][y] = 1;
        scrawl(image, x - 1, y, target, source, move);
        scrawl(image, x + 1, y, target, source, move);
        scrawl(image, x, y - 1, target, source, move);
        scrawl(image, x, y + 1, target, source, move);
    }

    public static void main(String[] args) {
        Solution733 solution733 = new Solution733();
        int [][] ints = solution733.floodFill(new int[][] {{0,0,0},{1,0,0}},1, 0, 2);
        for (int i = 0; i < ints.length; i ++) {
            for (int j = 0; j < ints[i].length; j++) {
                System.err.print(" "+ ints[i][j]);
            }
            System.err.println();
        }

    }

    public static class Solution200 {

        public int numIslands(char[][] grid) {
            int[][] point = new int[grid.length][grid[0].length];
            int count = 0;
            int x = grid.length, y = grid[0].length;
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    if (point[i][j] == 0 && grid[i][j] == '1') {
                        count += islet(grid, i, j, point);
                    }
                }
            }
            return count;
        }

        private int islet(char[][] grid, int x, int y, int[][] point) {
            if (x < 0 || y < 0 || x == grid.length || y == grid[0].length) {
                return 1;
            }
            if (point[x][y] == 1 || grid[x][y] == '0') {
                return 1;
            }
            point[x][y] = 1;
            int max = 0;
            max = Math.max(islet(grid, x + 1, y, point), max);
            max = Math.max(islet(grid, x - 1, y, point), max);
            max = Math.max(islet(grid, x, y - 1, point), max);
            max = Math.max(islet(grid, x, y + 1, point), max);
            return max;
        }

        public static void main(String[] args) {
            char[][] a = new char[][] {
                    {'1','1','1','1','0'},
                    {'1','1','0','1','0'},
                    {'1','1','0','0','0'},
                    {'0','0','0','0','0'}
            };
            Solution200 solution200 = new Solution200();

            System.err.println(solution200.numIslands(a));
        }
    }
}
